/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2005-8-4
 * Time: 15:48:05
 */
public class MailUtil
{
    public static final int MAX_MESSAGES_PER_TRANSPORT = 100;

    private static Logger log = LoggerFactory.getLogger(MailUtil.class);

    private MailUtil()
    {// prevent instantiation
    }

    //private static MailOptions mailOption = new MailOptions();

    /**
     * Get the user name part of an email. Ex: input: testaio@yahoo.com => output: testaio
     *
     * @param mail String the email
     * @return String the user name part of an email
     */
    public static String getEmailUsername(String mail)
    {
        if (mail == null) return StringUtil.empty;
        int atIndex = mail.indexOf('@');
        if (atIndex == -1)
        {
            return StringUtil.empty;
        }
        return mail.substring(0, atIndex);
    }

    /**
     * Get the domain part of an email. Ex: input: testaio@yahoo.com => output: yahoo.com
     *
     * @param mail String the email
     * @return String the user name part of an email
     */
    public static String getMailDomain(String mail)
    {
        if (mail == null) return StringUtil.empty;
        int atIndex = mail.indexOf('@');
        if (atIndex == -1)
        {
            return StringUtil.empty;
        }
        return mail.substring(atIndex + 1);
    }

    /**
     * Check if an email is good and safe or not.
     * This method should be use for all email input from user
     *
     * @param input String
     */
    public static boolean checkGoodMail(String input)
    {
        if (input == null) return false;
        int atIndex = input.indexOf('@');
        int dotIndex = input.lastIndexOf('.');
        if ((atIndex == -1) || (dotIndex == -1) || (atIndex >= dotIndex))
        {
            return false;
        }

        // now impl for content of the string
        int length = input.length();
        char c;

        for (int i = 0; i < length; i++)
        {
            c = input.charAt(i);
            if ((c >= 'a') && (c <= 'z'))
            {
                // lower char
            } else if ((c >= 'A') && (c <= 'Z'))
            {
                // upper char
            } else if ((c >= '0') && (c <= '9')/* && (i != 0)*/)
            {
                // as of 31 Jan 2004, i relax the email checking
                // so that the email can start with an numeric char
                // hopefully it does not introduce a security bug
                // because this value will be inserted into sql script

                // numeric char
            } else if (((c == '_') || (c == '-') || (c == '.') || (c == '@')) && (i != 0))
            {
                // _ char
            } else
            {
                return false;
            }
        }// for

        // last impl
        try
        {
            new javax.mail.internet.InternetAddress(input);
        } catch (Exception ex)
        {
            log.error("Error when running checkGoodMail", ex);
            return false;
        }
        return true;
    }


    /**
     * This method trim the email variable, so if it contains only spaces,
     * then it will be empty string, then we have 0 token :-)
     * The returned value is never null
     */
    public static String[] getMails(String mail) throws Exception
    {
        if (mail == null) mail = StringUtil.empty;
        mail = mail.trim();// very important
        mail = mail.replace(',', ';');// replace all occurrence of ',' to ';'
        StringTokenizer t = new StringTokenizer(mail, StringUtil.SEMICOLON);
        String[] ret = new String[t.countTokens()];
        int index = 0;
        while (t.hasMoreTokens())
        {
            String mails = t.nextToken().trim();
            checkGoodMail(mails);
            ret[index] = mails;
            //log.debug(ret[index]);
            index++;
        }
        return ret;
    }

    public static String[] getMails(String to, String cc, String bcc) throws Exception
    {
        String[] toMail = getMails(to);
        String[] ccMail = getMails(cc);
        String[] bccMail = getMails(bcc);
        String[] ret = new String[toMail.length + ccMail.length + bccMail.length];
        int index = 0;
        for (String aToMail : toMail)
        {
            ret[index] = aToMail;
            index++;
        }
        for (String aCcMail : ccMail)
        {
            ret[index] = aCcMail;
            index++;
        }
        for (String aBccMail : bccMail)
        {
            ret[index] = aBccMail;
            index++;
        }
        return ret;
    }
}